package cn.iocoder.yudao.module.system.controller.admin.gugu;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.system.controller.admin.gugu.convert.ScoreSegmentConvert;
import cn.iocoder.yudao.module.system.controller.admin.gugu.vo.ScoreSegmentRespVO;
import cn.iocoder.yudao.module.system.dal.dataobject.gugu.ScoreSegmentDO;
import cn.iocoder.yudao.module.system.service.gugu.ScoreSegmentService;
import cn.iocoder.yudao.module.system.util.gugu.GuGuDataUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Tag(name = "管理后台 - 高考一分一段数据")
@RestController
@RequestMapping("/system/score-segment")
@Validated
@Slf4j
public class ScoreSegmentController {

    @Resource
    private ScoreSegmentService scoreSegmentService;

    @GetMapping("/fetch")
    @Operation(summary = "获取高考一分一段数据")
    @PermitAll
    public CommonResult<Map<String, Object>> fetchScoreSegment(
            @Parameter(description = "APPKEY", required = true) @RequestParam(value = "appkey") String appkey) {

        // 验证appkey是否有效
        if (!GuGuDataUtils.validateScoreApiKey(appkey)) {
            return CommonResult.error(403, "无效的APPKEY");
        }

        // 所有省份列表
//        String province = "上海,云南,内蒙古,北京,台湾,吉林,四川,天津,宁夏,安徽,山东,山西,广东,广西,新疆,江苏,江西,河北,河南,浙江,海南,湖北,湖南,甘肃,福建,西藏,贵州,辽宁,重庆,陕西,青海,香港,黑龙江";
        String province = "广西";
        String[] provinceArray = province.split(",");

        // 不分文理科的省份列表（使用综合类型）
        String[] comprehensiveProvinces = new String[]{"上海", "浙江", "山东", "海南", "北京", "天津", "西藏"};

        // 使用文科/理科分类的省份列表
        String[] traditionalProvinces = new String[]{"广西"};

        // 创建省份类型映射，方便快速查找
        Set<String> comprehensiveSet = new HashSet<>(Arrays.asList(comprehensiveProvinces));
        Set<String> traditionalSet = new HashSet<>(Arrays.asList(traditionalProvinces));

        // 记录处理结果
        Map<String, Object> result = new HashMap<>();
        List<String> processedData = new ArrayList<>();
        List<String> errors = new ArrayList<>();

        // 循环年份
        for (String year : "2022".split(",")) {
            // 循环省份
            for (String provinceName : provinceArray) {
                try {
                    // 根据省份类型确定科目选择
                    if (comprehensiveSet.contains(provinceName)) {
                        // 不分文理科的省份，使用综合类型
                        Map<String, Object> response = scoreSegmentService.fetchAndSaveScoreSegment(appkey, year, provinceName, "综合");
                        processedData.add(String.format("年份: %s, 省份: %s, 科目: 综合", year, provinceName));
                        log.info("成功获取数据 - 年份: {}, 省份: {}, 科目: 综合", year, provinceName);
                    } else if (traditionalSet.contains(provinceName)) {
                        // 使用文科/理科分类的省份
                        scoreSegmentService.fetchAndSaveScoreSegment(appkey, year, provinceName, "文科");
                        // 添加请求间隔，避免触发API限制
                        Thread.sleep(1000);
                        scoreSegmentService.fetchAndSaveScoreSegment(appkey, year, provinceName, "理科");
                        processedData.add(String.format("年份: %s, 省份: %s, 科目: 文科,理科", year, provinceName));
                        log.info("成功获取数据 - 年份: {}, 省份: {}, 科目: 文科,理科", year, provinceName);
                    } else {
                        // 其他省份，使用物理类/历史类
                        scoreSegmentService.fetchAndSaveScoreSegment(appkey, year, provinceName, "物理类");
                        // 添加请求间隔，避免触发API限制
                        Thread.sleep(1000);
                        scoreSegmentService.fetchAndSaveScoreSegment(appkey, year, provinceName, "历史类");
                        processedData.add(String.format("年份: %s, 省份: %s, 科目: 物理类,历史类", year, provinceName));
                        log.info("成功获取数据 - 年份: {}, 省份: {}, 科目: 物理类,历史类", year, provinceName);
                    }

                    // 每个省份处理完成后添加间隔，避免请求过快
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    String errorMsg = String.format("线程中断 - 年份: %s, 省份: %s", year, provinceName);
                    errors.add(errorMsg);
                    log.error(errorMsg, e);
                    break; // 线程中断时退出循环
                } catch (Exception e) {
                    String errorMsg = String.format("处理数据失败 - 年份: %s, 省份: %s, 错误: %s", year, provinceName, e.getMessage());
                    errors.add(errorMsg);
                    log.error(errorMsg, e);
                }
            }
        }

        // 返回处理结果
        result.put("success", true);
        result.put("message", "数据获取任务已完成");
        result.put("processedData", processedData);
        if (!errors.isEmpty()) {
            result.put("errors", errors);
        }
        return CommonResult.success(result);
    }

    @GetMapping("/list")
    @Operation(summary = "查询高考一分一段数据列表")
    @PermitAll
    public CommonResult<List<ScoreSegmentRespVO>> getScoreSegmentList(
            @Parameter(description = "查询的年份，如 2020、2021、2022、2023、2024", required = true) @RequestParam(value = "year") String year,
            @Parameter(description = "省份名称，如：北京、上海、江苏等", required = true) @RequestParam(value = "provincename") String provinceName,
            @Parameter(description = "科目选择类型，如：物理类、历史类等", required = true) @RequestParam(value = "subjectselection") String subjectSelection) {

        // 从数据库获取数据
        List<ScoreSegmentDO> scoreSegmentList = scoreSegmentService.getScoreSegmentList(year, provinceName, subjectSelection);

        // 转换为VO对象
        return CommonResult.success(ScoreSegmentConvert.INSTANCE.convertList(scoreSegmentList));
    }

    @GetMapping("/by-score")
    @Operation(summary = "根据分数查询高考一分一段数据")
    @PermitAll
    public CommonResult<ScoreSegmentRespVO> getScoreSegmentByScore(
            @Parameter(description = "查询的年份，如 2020、2021、2022、2023、2024", required = true) @RequestParam(value = "year") String year,
            @Parameter(description = "省份名称，如：北京、上海、江苏等", required = true) @RequestParam(value = "provincename") String provinceName,
            @Parameter(description = "科目选择类型，如：物理类、历史类等", required = true) @RequestParam(value = "subjectselection") String subjectSelection,
            @Parameter(description = "高考分数", required = true) @RequestParam(value = "score") String score) {

        // 从数据库获取数据
        ScoreSegmentDO scoreSegment = scoreSegmentService.getScoreSegmentByScore(year, provinceName, subjectSelection, score);

        if (scoreSegment == null) {
            return CommonResult.error(404, "未找到相关数据");
        }

        // 转换为VO对象
        return CommonResult.success(ScoreSegmentConvert.INSTANCE.convert(scoreSegment));
    }

    @GetMapping("/by-condition")
    @Operation(summary = "根据条件查询高考一分一段数据")
    @PermitAll
    public CommonResult<List<ScoreSegmentRespVO>> getScoreSegmentByCondition(
            @Parameter(description = "查询的年份，如 2020、2021、2022、2023、2024", required = true) @RequestParam(value = "year") String year,
            @Parameter(description = "省份名称，如：北京、上海、江苏等", required = true) @RequestParam(value = "provincename") String provinceName,
            @Parameter(description = "科目选择类型，如：物理类、历史类等", required = true) @RequestParam(value = "subjectselection") String subjectSelection,
            @Parameter(description = "最小分数", required = false) @RequestParam(value = "minscore", required = false) String minScore,
            @Parameter(description = "最大分数", required = false) @RequestParam(value = "maxscore", required = false) String maxScore,
            @Parameter(description = "批次名称，如：本科批", required = false) @RequestParam(value = "batchname", required = false) String batchName) {

        // 从数据库获取数据
        List<ScoreSegmentDO> scoreSegmentList = scoreSegmentService.getScoreSegmentListByCondition(year, provinceName, subjectSelection,
                                                                                               minScore, maxScore, batchName);

        if (scoreSegmentList.isEmpty()) {
            return CommonResult.success(Collections.emptyList());
        }

        // 转换为VO对象
        return CommonResult.success(ScoreSegmentConvert.INSTANCE.convertList(scoreSegmentList));
    }
}
